<template>
  <div style="padding: 20px">
    <div class="msgDiv">
      <div>
        <el-form ref="form" :model="formData" label-width="120px">
          <!-- 基础信息 -->
          <div style="font-weight: bold;">基础信息</div>
          <div style="margin: 20px;">
            <el-form-item label="分销商等级名称" :required="true">
              <el-input style="width: 30%" v-model="formData.rule_name" class="input_css" placeholder="请输入分销商等级名称"></el-input>
            </el-form-item>
            <!-- <el-form-item label="等级排序" :required="true">
               <el-input v-model="form.phone" class="input_css" placeholder="请输入等级排序"></el-input><span class="tips_css" style="margin: 0;">(数字越大，级别越高)</span>
             </el-form-item> -->
            <el-form-item label="规则级别" :required="true">
              <el-input style="width: 30%" v-model="formData.grade" class="input_css" placeholder="规则级别"></el-input>
              <span class="tips_css" style="margin-left: 15px;">(数字越大，级别越高)</span>
            </el-form-item>
            <el-form-item label="佣金比率" :required="true">
              <span>(小于1，只保留两位小数)</span>
              <div style="margin-top: 10px;">
                <el-input
                  onkeyup="value = value.replace(/[^\d.]/g,'')" oninput="if(value.length>4)value=value.slice(0,4)"
                  style="width: 30%" v-model="formData.first_ratio" class="input_css" placeholder="请输入一级分销佣金比率">
                  <!--<template slot="append">%</template>-->
                </el-input>
                <!--<span>一级分销佣金比率</span>-->
              </div>
              <div style="margin-top: 10px;">
                <el-input
                  onkeyup="value = value.replace(/[^\d.]/g,'')" oninput="if(value.length>4)value=value.slice(0,4)"
                  style="width: 30%" v-model="formData.secondary_ratio" class="input_css"
                          placeholder="请输入二级分销佣金比率">
                  <!--<template slot="append">%</template>-->
                </el-input>
                <!--<span>二级分销佣金比率</span>-->
              </div>
              <div style="margin-top: 10px;">
                <el-input
                  onkeyup="value = value.replace(/[^\d.]/g,'')" oninput="if(value.length>4)value=value.slice(0,4)"
                  style="width: 30%" v-model="formData.three_ratio" class="input_css" placeholder="请输入三级分销佣金比率">
                  <!--<template slot="append">%</template>-->
                </el-input>
                <!--<span>三级分销佣金比率</span>-->
              </div>
            </el-form-item>
            <el-form-item label="自动升级">
              <el-radio v-model="formData.auto_upgrade" :label="1">支持</el-radio>
              <el-radio v-model="formData.auto_upgrade" :label="0">不支持</el-radio>
            </el-form-item>
            <el-form-item label="默认等级">
              <el-radio v-model="formData.is_default" :label="1">是</el-radio>
              <el-radio v-model="formData.is_default" :label="0">否</el-radio>
              <div style="font-size: 14px;color: grey">注：即成为分销商时的初始分销等级</div>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="formData.status">
                <el-option :value="1" :label="'开启'"></el-option>
                <el-option :value="0" :label="'关闭'"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="背景图片">
              <el-upload
                class="avatar-uploader"
                name="photo"
                :action="$api.UPLOAD_IMG"
                :show-file-list="false"
                :on-success="addUploadSuccessByBg"
              >


                <img v-if="bg_img_url" :src="bg_img_url" class="avatar">
                <div v-else style="display: flex;align-items: center;flex-direction: column;font-size: 11px;color: grey;line-height: 15px;padding-bottom: 10px" >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <span style="margin-top: 10px;">宽高比例为750:430</span>
                  <span>文件大小<2Mb</span>
                  <span>不设置则默认背景色为绿色</span>
                </div>
                <!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <span>宽高比例为750:430</span>
                <span>文件大小<2Mb</span>-->
              </el-upload>
              <el-button v-if="bg_img_url" type="text" style="color: red;float: left" @click="deleteImg">删除</el-button>
            </el-form-item>
            <!--<el-form-item label="描述">
              <vue-ueditor-wrap  v-model="formData.detail" :config="myConfig"></vue-ueditor-wrap>
            </el-form-item>-->
          </div>

          <div>
            <div style="font-weight: bold;">
              <span>升级条件</span>
              <span style="font-weight: normal;font-size: 14px;color: #333333;margin-left: 16px;font-weight: 600;">满足条件为{{upgradeConditionsStr}}</span>
            </div>
            <div style="margin-left: 80px;color: #BBBBBB;font-size: 14px">
              <p>注：1.若条件为空或为0，即表示人人满足</p>
              <p style="margin-left: 30px">2.例如：希望B条件设置为不使用，则至少设置一个“与”的规则，可以设置为“A与B或C”,也可以设置为“A或B与C”</p>
            </div>
            <div style="margin: 20px;">

              <!--<el-form-item label="升级到的规则">
                <el-select filterable v-model="formData.upgrade_option_arr.to_rule_id">
                  <el-option v-for="(item,index) in distributionRuleList" :key="index" :value="item.id" :label="item.rule_name"></el-option>
                </el-select>
              </el-form-item>-->

              <el-form-item label="A">
                <div>
                  <span style="margin-right: 12px;">累计发展下级分销商数量达到</span>
                  <el-input style="width: 200px;" v-model="formData.upgrade_option_arr.son_user_limit" class="input_css" placeholder="请输入人数">
                    <template slot="append">人</template>
                  </el-input>
                </div>
                <div style="margin-top: 15px;">
                  <span @click="changeAndOrRelation('son_user_require',0)" :class="{'btnAndOr_css': true,'is_selected': this.formData.upgrade_option_arr.son_user_require==0}">或</span>
                  <span @click="changeAndOrRelation('son_user_require',1)" :class="{'btnAndOr_css': true,'is_selected': this.formData.upgrade_option_arr.son_user_require==1}">与</span>
                </div>
              </el-form-item>

              <el-form-item label="B">
                <div>
                  <span style="margin-right: 12px;">指定购买商品</span>
                  <el-button size="mini" type="primary" @click="chooseGoodsDialog = true">添加</el-button>
                  <div style="margin-left: -20px;color: #BBBBBB;font-size: 14px">注：若添加了多个商品，即表示需要购买所有指定商品设置的数量才满足此条件</div>
                  <el-table v-if="selectGoodsData.length>0" stripe :data="selectGoodsData"
                            style="width: 80%;margin-top: 10px;" class="el_table_style"
                            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                            :default-sort="{prop: 'stock', order: 'descending'}">
                    <el-table-column label="商品ID" prop="id"></el-table-column>
                    <el-table-column label="UPC码" prop="upc"></el-table-column>
                    <el-table-column label="封面图">
                      <template slot-scope="scope">
                        <div v-if="scope.row">
                          <img :src="scope.row.thumb_url" alt="" style="width:50px;height:50px;object-fit:cover;margin-right: 15px">
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="所需购买数量" prop="name">
                      <template slot-scope="scope" v-if="scope.row">
<!--                        <el-input size="mini" type="number" style="width: 100px" v-model="selectGoodsData[scope.row.index].buy_num"></el-input>-->
                        <el-input size="mini" type="number" style="width: 100px" v-model="scope.row.buy_num"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-button type="text" style="color: red" @click="deleteSelectGoods(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                  <!--<div class="page-code">
                    <el-pagination
                      background :current-page="tablePage" :page-size="5" layout="prev, pager, next" :total="selectGoodsData.length" @current-change="pageChange">
                    </el-pagination>
                  </div>-->

                  <div style="margin-top: 20px;">
                    <span @click="changeAndOrRelation('distribution_money_require',0)" :class="{'btnAndOr_css': true,'is_selected': this.formData.upgrade_option_arr.distribution_money_require==0}">或</span>
                    <span @click="changeAndOrRelation('distribution_money_require',1)" :class="{'btnAndOr_css': true,'is_selected': this.formData.upgrade_option_arr.distribution_money_require==1}">与</span>
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="C">
                <div>
                  <span style="margin-right: 12px;">累计分销订单金额达到</span>
                  <el-input style="width: 200px;" v-model="formData.upgrade_option_arr.distribution_money_limit" class="input_css" placeholder="请输入">
                    <template slot="append">元</template>
                  </el-input>
                </div>
              </el-form-item>

            </div>
          </div>
        </el-form>

        <div style="text-align: center;">
          <el-button type="success" @click="submitBtn()">{{formData.id?'修改':'添加'}}</el-button>
        </div>
      </div>

      <el-dialog :title="'选择商品'" :visible.sync="chooseGoodsDialog">
        <choose-goods :componentTempData="selectGoodsData" @hideModelMsgDialog="hideModelMsgDialog" />
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import choose_goods from "@/views/distributionManage/components/choose_goods";
  import VueUeditorWrap from 'vue-ueditor-wrap'

  export default {
    components: {
      "choose-goods": choose_goods,
      VueUeditorWrap,
    },
    props: {
      item: ''
    },
    watch: {
      item(val){
        if(val){
          this.initData()
        }
      },
      chooseGoodsDialog(val){
        if(!val){

        }
      },
      "formData.upgrade_option_arr.son_user_require"() {
        this.calculateUpgradeConditionsStr()
      },
      "formData.upgrade_option_arr.distribution_money_require"() {
        this.calculateUpgradeConditionsStr()
      }
    },
    data() {
      return {
        formData: {
          "id": 4,
          "rule_name": "",
          "grade": 0,
          "first_ratio": "",
          "secondary_ratio": "",
          "three_ratio": "",
          "auto_upgrade": 0,
          "is_default": 0,
          "status": 1,
          "upgrade_option_arr": {
            "id": "0",
            "to_rule_id": "0",
            "son_user_limit": "",
            "son_user_require": 0,
            "distribution_money_limit": "",
            "distribution_money_require": 0,
            "goods_list": []
          },
          "bg_img_id": '',
          "detail": ''
        },
        bg_img_url: '',
        distributionRuleList: [],
        selectGoodsData: [],
        tableData: [],
        chooseGoodsDialog: false,
        testArr: [],
        tablePage: 1,
        componentTempData: [],
        upgradeConditionsStr: '',
        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 300,
          // 初始容器宽度
          initialFrameWidth: '40%',
          // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
          // serverUrl: 'http://35.201.165.105:8000/controller.php',
          serverUrl: 'https://wxapp.gdhrma.org.cn/ueditor-php/controller.php',
          // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
          //UEDITOR_HOME_URL: '/peoples_association_backstage/dist//static/UEditor/'
          UEDITOR_HOME_URL: '/UEditor/',
          zIndex: 5,
          toolbars: [
            [
              'bold', 'italic', 'underline',
              'insertorderedlist', 'insertunorderedlist',
              'simpleupload', 'inserttable','link'
            ]
          ]
        },
      }
    },
    mounted() {
      this.initData()
      this.getDistributionRule()
      this.calculateUpgradeConditionsStr()
    },
    methods: {

      calculateUpgradeConditionsStr() {
        let first = ''
        let second = ''
        if(this.formData.upgrade_option_arr.son_user_require==1){
          first = '与'
        } else {
          first = '、'
        }
        if(this.formData.upgrade_option_arr.distribution_money_require==1){
          second = '与'
        } else {
          second = '、'
        }
        this.upgradeConditionsStr = 'A' + first + 'B' + second + 'C'
      },

      initData(){
        /*if (!this.item){
          return
        }*/
        let tempStr = window.localStorage.getItem("distribution_info")
        if(!tempStr){
          return;
        }
        let tempObj = JSON.parse(tempStr)
        if(!tempObj){
          return;
        }
        /*if(!this.$store.distributeItem){
          return
        }*/
        let item = tempObj//this.$store.distributeItem
        this.formData.id = item.id
        this.formData.rule_name = item.rule_name
        this.formData.grade = item.grade
        this.formData.first_ratio = item.first_ratio
        this.formData.secondary_ratio = item.secondary_ratio
        this.formData.three_ratio = item.three_ratio
        this.formData.status = item.status
        this.formData.is_default = item.is_default
        this.formData.auto_upgrade = item.auto_upgrade
        this.formData.detail = item.detail
        this.formData.bg_img_id = item.bg_img_id
        this.bg_img_url = item.bg_img_url

        if(!item.upgrade_option_arr || item.upgrade_option_arr.length==0){
          return
        }

        this.formData.upgrade_option_arr.distribution_money_require = item.upgrade_option_arr[0].distribution_money_require
        this.formData.upgrade_option_arr.distribution_money_limit = item.upgrade_option_arr[0].distribution_money_limit
        this.formData.upgrade_option_arr.son_user_require = item.upgrade_option_arr[0].son_user_require
        this.formData.upgrade_option_arr.son_user_limit = item.upgrade_option_arr[0].son_user_limit
        /*this.formData.upgrade_option_arr.to_rule_id = parseInt(item.upgrade_option_arr[0].to_rule_id)*/
        this.formData.upgrade_option_arr.id = item.upgrade_option_arr[0].id

        let tempGoodsData = []
        let arr = []
        item.upgrade_option_arr[0].goods_list.forEach((item,index) => {
          let obj = {
            id: item.goods_id,
            upc: item.upc,
            thumb_url: item.thumb_url,
            name: item.name,
            index: index,
            buy_num: item.num_require
          }
          tempGoodsData.push(obj)
        })

        this.selectGoodsData = tempGoodsData
        this.componentTempData = tempGoodsData

      },

      hideModelMsgDialog(items) {
        this.chooseGoodsDialog = false
        let tempActivityArr = this.testArr
        this.testArr = []
        this.selectGoodsData = items.map((item,index)=>{
          if(!item.buy_num){

          }
          let obj = {
            id: item.id,
            upc: item.upc,
            thumb_url: item.thumb_url,
            name: item.name,
            index: index,
            buy_num: item.buy_num || 0
          }
          return obj
        })
        console.log('打印看看',this.selectGoodsData)
      },

      changeAndOrRelation(type,data) {
        if(type==='son_user_require'){
          this.formData.upgrade_option_arr.son_user_require = data
        } else {
          this.formData.upgrade_option_arr.distribution_money_require = data
        }
      },

      async getDistributionRule(){
        let params = {
          limit: 99,
          page: 1
        }
        const res = await this.$api.getDistributionRule(params);
        if(res.data.level=='success'){
          let list = res.data.data;
          this.distributionRuleList = list;
        }else {
          this.$message.error(res.data.message)
        }
      },

      pageChange(e) {
        this.tablePage = e
        let start = (e - 1) * 5
        let end = start + 5
        this.tableData = this.selectGoodsData.slice(start,end)
        console.log('分页这里',this.tableData)
      },

      deleteSelectGoods(row) {
        let index = this.selectGoodsData.indexOf(row)
        this.selectGoodsData.splice(index,1)
      },

      async submitBtn() {

        //设置商品数据
        let tempGoodsData = []
        this.selectGoodsData.forEach((item,index) => {
          let obj = {
            goods_id: item.id,
            num_require: item.buy_num
          }
          tempGoodsData.push(obj)
        })
        this.formData.upgrade_option_arr.goods_list = tempGoodsData
        let params = this.formData
        params.upgrade_option_arr = [this.formData.upgrade_option_arr]

        const res = await this.$api.setDistributionRule(params)
        if (res.data.level === 'success') {
          this.$router.back()
        } else {
          this.$message.error(res.data.message)
        }
        this.$message({type: res.data.level, message: res.data.message,duration: 1500})
      },

      addUploadSuccessByBg(res, file) {
        if(res.data){
          this.bg_img_url = res.data.img_url;
          this.formData.bg_img_id = res.data.id;
        }
      },

      deleteImg() {
        this.bg_img_url = ''
        this.bg_img_id = ''
      }

    }
  }
</script>

<style scoped>
  .btnAndOr_css{
    display: inline-block;
    width: 45px;
    height: 45px;
    line-height: 45px;
    text-align: center;
    border-radius: 50%;
    background: #bbb;
    margin-right: 30px;
    color: #fff;
    cursor: pointer;
  }
  .is_selected{
    background-color: #67c23a;
  }
  .page-code{
    margin-top: 15px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 130px;
    height: 130px;
    line-height: 130px;
    text-align: center;
    border: 1px solid #ececec;
  }

  .avatar {
    width: 150px;
    height: auto;
    display: block;
  }
</style>
<style scoped>
  /deep/.el-table td, /deep/.el-table th {
    text-align: center;
  }
  /deep/.el-table .warning-row {
    background: #f8f9fa;
  }

  /deep/.el-table .success-row {
    background: #ffffff;
  }
  /deep/.el_table_style{
    border: 1px solid #dee2e6;
  }
  /deep/.el-table td {
    border: none;
  }
  /deep/.el-table th{
    padding: 0 !important;
  }
</style>
